// index.js
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

Page({
  data: {
    audioInfo: {
      currentTime: "00:00",
      duration: "00:00"
    },
    isPlay: false,
    audioTime: ''
  },
  onLoad() {
    const that = this;
    this.innerAudioContext = wx.createInnerAudioContext()
    this.innerAudioContext.src = 'https://jqadmin.tangshannanhu.com/api/upload/ab6d95b0-0977-4012-ac31-dc238d63be7f.mp3';
    this.innerAudioContext.volume = 1;
    
    // 先注册事件回调，再调用play方法
    this.innerAudioContext.onPlay(function (e) {
      console.log('onPlay 回调')
      if ("00:00" === that.data.audioInfo.duration) {
        var n = setInterval(function() {
          if (0 !== that.innerAudioContext.duration) {
            clearInterval(n);
            // 仅在首次加载获取时长，不停止音频
            var duration = that.innerAudioContext.duration;
            that.setData({
              audioInfo: {
                ...that.data.audioInfo,
                duration: that.handlerDealTime(duration).min + ':' + that.handlerDealTime(duration).sec
              }
            })
            console.log(that.data.audioInfo.duration);
          }
        }, 500)
      }
    })
    
    this.innerAudioContext.onPause(function(e) {
      console.log('onPause 回调')
    })
    
    // 注册onTimeUpdate回调，只需要注册一次
    this.innerAudioContext.onTimeUpdate(function() {
      console.log('onTimeUpdate 回调')
      that.setData({
        audioInfo: {
          ...that.data.audioInfo,
          currentTime: "".concat(
            that.handlerDealTime(that.innerAudioContext.currentTime).min, ":"
          ).concat(that.handlerDealTime(that.innerAudioContext.currentTime).sec)
        }
      })
      // 播放完成判断
      if (Math.abs(that.innerAudioContext.currentTime - that.innerAudioContext.duration) < 0.1) {
        that.setData({
          isPlay: false,
          audioInfo: {
            ...that.data.audioInfo,
            currentTime: "00:00"
          },
        })
        // 重置音频位置
        that.innerAudioContext.seek(0);
      }
    });
    
    // 注册onCanplay回调
    this.innerAudioContext.onCanplay(function() {
      console.log('onCanplay 回调')
      return that.innerAudioContext.duration;
    });
  },
  audioPlayed() {
    const that = this;
    this.setData({
      isPlay: !this.data.isPlay
    })
    if (this.data.isPlay) {
      console.log('执行 play方法')
      // 播放音频
      this.innerAudioContext.play();
    } else {
      console.log('执行 pause方法')
      // 暂停音频
      this.innerAudioContext.pause();
    }
  },
  handlerDealTime: function(e) {
    var n = e.toString().split(".")[0] % 60,
      t = n < 10 ? "0".concat(n) : "".concat(n),
      i = e.toString().split(".")[0] / 60;
    return {
      min: i < 1 ? "00" : i < 10 ? "0".concat(parseInt(i)) : "".concat(parseInt(i)),
      sec: t
    }
  },
})
